<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>贪吃蛇绘制二次代码编辑</title>
    <style>
        canvas {
            display: block;
            margin: 0 auto;
            background-color: #33cc99;
        }
    </style>
</head>

<body>
    <canvas width="500" height="500" id="huabu"></canvas>
</body>
<script>
    let huabu = document.getElementById('huabu');
    let tol = huabu.getContext('2d');

    let x = Math.floor(Math.random() * 20) * 25;
    let y = Math.floor(Math.random() * 20) * 25;

    let isEated = false;

    let snake = [{
        x: 3,
        y: 0
    }, {
        x: 2,
        y: 0
    }, {
        x: 1,
        y: 0
    }];

    let directionX = 1;
    let directionY = 0;

    let isGameOver = false;

    document.addEventListener('keydown', (e) => {
        let k = e.keyCode;
        if (k === 38) {
            directionX = 0;
            directionY = -1
        } else if (k === 40) {
            directionX = 0;
            directionY = 1
        } else if (k === 37) {
            directionX = -1;
            directionY = 0
        } else if (k === 39) {
            directionX = 1;
            directionY = 0
        }
    });

    setInterval(() => {
        if (isGameOver) {
            return
        }

        tol.clearRect(0, 0, 500, 500);

        if (isEated) {
            x = Math.floor(Math.random() * 20) * 25;
            y = Math.floor(Math.random() * 20) * 25;
        }

        tol.fillStyle = '#fff000';
        tol.fillRect(x, y, 25, 25);

        let oldHead = snake[0];
        let newHead = {
            x: oldHead.x + directionX,
            y: oldHead.y + directionY
        }

        if (newHead.y < 0 || newHead.x < 0 || newHead.x * 30 >= 600 || newHead.y * 30 >= 600) {
            isGameOver = true;
            alert('Game over···请刷新页面重新游戏')
        } else {
            snake.unshift(newHead);
            if (snake[0].x * 25 === x && snake[0].y * 25 === y) {
                isEated = true;
            } else {
                isEated = false;
                snake.pop();
            }
        }

        for (var i = 0; i < snake.length; i++) {
            if (i === 0) {
                tol.fillStyle = 'purple';
            } else {
                tol.fillStyle = 'blue';
            }
            tol.fillRect(snake[i].x * 25, snake[i].y * 25, 25, 25);
        }

        for (let i = 1; i < 20; i++) {
            tol.moveTo(0, 25 * i + 0.5);
            tol.lineTo(500, 25 * i + 0.5);
            tol.moveTo(25 * i + 0.5, 0);
            tol.lineTo(25 * i + 0.5, 500);
        }

        tol.strokeStyle = 'white';
        tol.stroke();
    }, 300)
</script>

</html>